﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace dzs.Web.Outstorage
{
    public partial class SubmitProject : Web.Admin.BasePage
	{
		protected void Page_Load(object sender, EventArgs e)
		{
            if (!IsPostBack)
            {
                Session.Remove("li_outList");//移除出库单

                if (Session["login"] != null)
                {
                    DataSet ds = Session["login"] as DataSet;
                    int roles_id = Convert.ToInt32(ds.Tables[0].Rows[0]["roles_id"].ToString());
                    int user_id =Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());
                    string user_name = ds.Tables[0].Rows[0]["user_name"].ToString();

                    dzs.BLL.user u = new BLL.user();

                    DataSet ds_check = u.GetUserCheck(" cly_id=" + user_id);

                    this.ddl_checkUser.DataSource = ds_check;
                    this.ddl_checkUser.DataTextField = "user_name";
                    this.ddl_checkUser.DataValueField = "check_id";
                    this.ddl_checkUser.DataBind();
                    this.ddl_checkUser.Items.Insert(0, new ListItem("--无--","-1"));


                    this.lbl_userName.Text = user_name;
                    
                }
                else
                {
                    Maticsoft.Common.MessageBox.Show(this, "由于长时间未操作，登录信息已过期，请重新登陆!");
                }
               
            }
		}
        //填写出库单
        protected void btn_selectProject_Click(object sender, EventArgs e)
        {
            BindGV();
            //this.ddl_project.Enabled = false;
            this.txt_projectName.Enabled = false;
        }

        private void BindGV()
        {
            //if (this.ddl_project.SelectedValue == "-1")
            //{
            //    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择出库项目！');</script>");
            //    return;
            //}
            if (string.IsNullOrEmpty(this.txt_projectName.Text))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择出库项目！');</script>");
                return;
            }

            dzs.BLL.inventory ven = new BLL.inventory();

            string where = " ";
            if (!string.IsNullOrEmpty(this.txt_material.Text))
            {
                where += " and material like '%" + this.txt_material.Text + "%' ";

            }

            string proid = this.txt_projectName.Text.Split('|')[1];

            //DataSet ds = ven.GetMaterialVentoryInfo(this.ddl_project.SelectedValue,where);
            DataSet ds = ven.GetMaterialVentoryInfo(proid, where);

            this.GridView1.DataSource = ds;
            this.GridView1.DataBind();


        }
        //加入出库单
        protected void btn_add_Click(object sender, EventArgs e)
        {
            #region 验证是否填写
            //if (this.ddl_checkUser.SelectedValue == "-1")
            //{
            //    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择审核人！');</script>");
            //    return;
            //}
            if (string.IsNullOrEmpty(this.txt_out_storage_Estimate.Text))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请填写出库时间！');</script>");
                return;
            }
            if (string.IsNullOrEmpty(this.txt_receive_address.Text))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请填写收货地点！');</script>");
                return;
            }
            if (string.IsNullOrEmpty(this.txt_receive_userName.Text))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请填写收货人！');</script>");
                return;
            }
            if (string.IsNullOrEmpty(this.txt_receive_userPhone.Text))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请填写收货人电话！');</script>");
                return;
            }
            #endregion

            string msg = CheckCboList();

            if (!string.IsNullOrEmpty(msg))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + msg + "');</script>");
            }
            else
            {
                if (Session["login"] != null)
                {
                    DataSet ds = Session["login"] as DataSet;

                    int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                    //获取选择的出库清单
                    List<dzs.Model.out_storageList> li = GetCboList(user_id, Convert.ToInt32(this.ddl_checkUser.SelectedValue));
                    //将前边页已选择的出库清单加入
                    if (Session["li_outList"] != null)
                    {
                        List<dzs.Model.out_storageList> li_session = Session["li_outList"] as List<dzs.Model.out_storageList>;

                        foreach (dzs.Model.out_storageList o in li_session)
                        {
                            li.Add(o);
                        }

                        Session["li_outList"] = li;
                    }
                    else
                    {
                        Session["li_outList"] = li;
                    }

                    BindGV2(li);
                    BindGV();
                }
                else
                {
                    Maticsoft.Common.MessageBox.Show(this, "由于长时间未操作，登录信息已过期，请重新登陆!");
                }

            }

            //this.ddl_project.Enabled = false;

            this.txt_projectName.Enabled = false;

        }
        //绑定出库清单
        private void BindGV2(List<dzs.Model.out_storageList> li)
        {
            ////获取选择的出库清单
            //List<dzs.Model.out_storageList> li = GetCboList(user_id, Convert.ToInt32(this.ddl_checkUser.SelectedValue));
            ////将前边页已选择的出库清单加入
            //if (Session["li_outList"] != null)
            //{
            //    List<dzs.Model.out_storageList> li_session = Session["li_outList"] as List<dzs.Model.out_storageList>;

            //    foreach (dzs.Model.out_storageList o in li_session)
            //    {
            //        li.Add(o);
            //    }

            //    Session["li_outList"] = li;
            //}
            //else
            //{
            //    Session["li_outList"] = li;
            //}

            this.GridView2.DataSource = this.GetCboDataSet(li);
            this.GridView2.DataBind();
        }

        //提交审核
        protected void btn_submit_Click(object sender, EventArgs e)
        {
            if (Session["li_outList"] != null)
            {
                //string batchId = this.ddl_project.SelectedValue + "TIME" + System.DateTime.Now.ToString("yyyyMMddHHmmssffff");//出库单号
                string proid = this.txt_projectName.Text.Split('|')[1];
                string batchId = proid + "TIME" + System.DateTime.Now.ToString("yyyyMMddHHmmssffff");//出库单号

                List<dzs.Model.out_storageList> li = Session["li_outList"] as List<dzs.Model.out_storageList>;

                string msg = this.CheckOutList(li);//验证所填写出库单数量是否超出实际剩余量

                if (string.IsNullOrEmpty(msg))
                {
                    dzs.BLL.out_storageList om = new BLL.out_storageList();

                    foreach (dzs.Model.out_storageList o in li)
                    {
                        o.out_storageList_batchID = batchId;//出库清单号
                        om.Add(o);
                    }

                    Session.Remove("li_outList");
                    if (Session["login"] != null)
                    {
                        DataSet ds = Session["login"] as DataSet;

                        int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                        BindGV2(li);
                        BindGV();
                    }

                    //ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('操作成功！您的出库清单号："+batchId+"');</script>");
                    Maticsoft.Common.MessageBox.Show(this, "操作成功！您的出库清单号：" + batchId);
                }
                else
                {
                    Maticsoft.Common.MessageBox.Show(this, msg);
                }


            }
            else
            {
                Maticsoft.Common.MessageBox.Show(this, "由于长时间未操作，信息已过期，请重新登陆!");
            }



        }

        //验证实际剩余数量与出库数量之差
        private string CheckCboList()
        {
            string msg = "";

            for (int i = 0; i < this.GridView1.Rows.Count; i++)
            {
                CheckBox cbo = this.GridView1.Rows[i].FindControl("cbo_check") as CheckBox;

                if (cbo != null && cbo.Checked)
                {
                    TextBox txt_out_storage_count = this.GridView1.Rows[i].FindControl("txt_out_storage_count") as TextBox;//预出库数量
                    Label lbl_material_id = this.GridView1.Rows[i].FindControl("lbl_material_id") as Label;//物料ID
                    Label lbl_realCount = this.GridView1.Rows[i].FindControl("lbl_realCount") as Label;//实际剩余数量

                    decimal out_count = 0;
                    decimal real_count = 0;
                    int mid = 0;

                    try
                    {
                        if (!string.IsNullOrEmpty(txt_out_storage_count.Text))
                        {
                            out_count = Convert.ToDecimal(txt_out_storage_count.Text);
                        }
                        else
                        {
                            msg += @"\n 请填写预出库数量！";
                        }
                    }
                    catch (Exception)
                    {

                        msg += @"\n 预出库量请填写数字！";
                    }

                    if (!string.IsNullOrEmpty(lbl_realCount.Text))
                    {
                        real_count = Convert.ToDecimal(lbl_realCount.Text);
                    }
                    if (!string.IsNullOrEmpty(lbl_material_id.Text))
                    {
                        mid = Convert.ToInt32(lbl_material_id.Text);
                    }

                    if (real_count - out_count < 0)
                    {
                        dzs.Model.materialinfo m = new dzs.BLL.materialinfo().GetModel(mid);

                        msg += @"\n “" + m.material + "”预出库数量大于实际剩余数量，请重新填写！";
                    }


                }
            }

            return msg;
        }
        //验证出库单
        private string CheckOutList(List<dzs.Model.out_storageList> li)
        {
            string msg = "";

            decimal count = 0;

            dzs.BLL.inventory ven = new BLL.inventory();

            string where = " ";
            if (!string.IsNullOrEmpty(this.txt_material.Text))
            {
                where += " and material like '%" + this.txt_material.Text + "%' ";

            }

            string proid = this.txt_projectName.Text.Split('|')[1];

            //DataSet ds = ven.GetMaterialVentoryInfo(this.ddl_project.SelectedValue,where);
            DataSet ds = ven.GetMaterialVentoryInfo(proid, where);

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                decimal real_count = Convert.ToDecimal(row["real_count"]);
                int material_id = Convert.ToInt32(row["mid"]);
                string material = Convert.ToString(row["material"]);

                count = real_count;
                foreach (dzs.Model.out_storageList o in li)
                {
                    if (o.material_id.Value == material_id)
                    {
                        count = count - o.out_storage_count.Value;
                    }
                }

                if (count < 0)
                {
                    msg += @"\n “" + material + "”";
                }


            }

            //for (int i = 0; i < this.GridView1.Rows.Count; i++)
            //{

            //    Label lbl_count = this.GridView1.Rows[i].FindControl("lbl_realCount") as Label;
            //    Label lbl_material_id = this.GridView1.Rows[i].FindControl("lbl_material_id") as Label;//物料ID
            //    Label lbl_material = this.GridView1.Rows[i].FindControl("lbl_material") as Label;//物料描述

            //    if (!string.IsNullOrEmpty(lbl_count.Text) && !string.IsNullOrEmpty(lbl_material_id.Text))
            //    {
            //        count = Convert.ToDecimal(lbl_count.Text.Trim());
            //        foreach (dzs.Model.out_storageList o in li)
            //        {
            //            if (o.material_id.Value == Convert.ToInt32(lbl_material_id.Text))
            //            {
            //                count = count - o.out_storage_count.Value;
            //            }
            //        }

            //        if (count < 0)
            //        {
            //            msg += @"\n “" + lbl_material .Text+ "”";
            //        }

            //    }

            //}

            if (!string.IsNullOrEmpty(msg))
            {
                msg += @"\n 申请出库量大于实际剩余量，请重新填写出库单！";
            }


            return msg;
        }
        private DataTable GetCboDataSet(List<dzs.Model.out_storageList> li)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("out_storage_count", Type.GetType("System.String"));//预出库数量
            dt.Columns.Add("material", Type.GetType("System.String"));//物料描述
            dt.Columns.Add("unit", Type.GetType("System.String"));//数量单位
            dt.Columns.Add("projectname", Type.GetType("System.String"));//项目名称
            dt.Columns.Add("proid", Type.GetType("System.String"));//项目编号
            dt.Columns.Add("mid", Type.GetType("System.String"));//物料ID

            foreach (dzs.Model.out_storageList o in li)
            {
                DataRow row = dt.NewRow();
                row["out_storage_count"] = o.out_storage_count;
                row["material"] = o.material;
                row["unit"] = o.unit;
                row["proid"] = o.proid;
                row["projectname"] = o.projectname;
                row["mid"] = o.material_id.ToString();

                dt.Rows.Add(row);
            }

            return dt;
        }

        //加入出库单操作
        private List<dzs.Model.out_storageList> GetCboList(int material_user_id, int check_user_id)
        {
            List<dzs.Model.out_storageList> li = new List<Model.out_storageList>();

            for (int i = 0; i < this.GridView1.Rows.Count; i++)
            {
                CheckBox cbo = this.GridView1.Rows[i].FindControl("cbo_check") as CheckBox;

                if (cbo != null && cbo.Checked)
                {
                    TextBox txt_out_storage_count = this.GridView1.Rows[i].FindControl("txt_out_storage_count") as TextBox;//预出库数量
                    //TextBox txt_out_storage_Estimate = this.GridView1.Rows[i].FindControl("txt_out_storage_Estimate") as TextBox;//预出库时间
                    //TextBox txt_receive_address = this.GridView1.Rows[i].FindControl("txt_receive_address") as TextBox;//到货地点
                    //TextBox txt_receive_userName = this.GridView1.Rows[i].FindControl("txt_receive_userName") as TextBox;//接收人
                    //TextBox txt_receive_userPhone = this.GridView1.Rows[i].FindControl("txt_receive_userPhone") as TextBox;//接收人电话

                    Label lbl_material_id = this.GridView1.Rows[i].FindControl("lbl_material_id") as Label;//物料ID
                    Label lbl_realCount = this.GridView1.Rows[i].FindControl("lbl_realCount") as Label;//实际剩余数量
                    Label lbl_material = this.GridView1.Rows[i].FindControl("lbl_material") as Label;//物料描述
                    Label lbl_unit = this.GridView1.Rows[i].FindControl("lbl_unit") as Label;//数量单位
                    Label lbl_proid = this.GridView1.Rows[i].FindControl("lbl_proid") as Label;//项目编号
                    Label lbl_projectname = this.GridView1.Rows[i].FindControl("lbl_projectname") as Label;//项目名称


                    dzs.Model.out_storageList o = new Model.out_storageList();
                    if (!string.IsNullOrEmpty(txt_out_storage_count.Text))
                    {
                        o.out_storage_count = Convert.ToDecimal(txt_out_storage_count.Text);
                    }
                    else
                    {
                        o.out_storage_count = 0;
                    }
                    if (!string.IsNullOrEmpty(txt_out_storage_Estimate.Text))
                    {
                        o.out_storage_Estimate = Convert.ToDateTime(txt_out_storage_Estimate.Text);
                    }
                    else
                    {
                        o.out_storage_Estimate = System.DateTime.Now;
                    }
                    o.material_id = Convert.ToInt32(lbl_material_id.Text);
                    o.material_user_id = material_user_id;
                    o.check_user_id = check_user_id;
                    o.receive_address = txt_receive_address.Text;
                    o.receive_userName = txt_receive_userName.Text;
                    o.receive_userPhone = txt_receive_userPhone.Text;
                    if (this.ddl_checkUser.SelectedValue == "-1")//如果审核人为“无”则默认为审核通过
                    {
                        o.check_status = "审核通过";
                    }
                    else
                    {
                        o.check_status = "未审核";
                    }
                    
                    o.deal_status = "未处理";
                    o.material = lbl_material.Text;
                    o.proid = lbl_proid.Text;
                    o.projectname = lbl_projectname.Text;
                    o.unit = lbl_unit.Text;

                    //if (ddl_targetProject.SelectedItem.Value != "-1")
                    //{
                    //    o.target_project = ddl_targetProject.SelectedItem.Value;
                    //}

                    o.target_project = this.txt_targetProject.Text;

                    li.Add(o);
                }
            }

            return li;
        }
        //翻页
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GridView1.PageIndex = e.NewPageIndex;
            BindGV();
        }

        //重新填写出库单
        protected void btn_re_Click(object sender, EventArgs e)
        {
            Session.Remove("li_outList");
            if (Session["login"] != null)
            {
                DataSet ds = Session["login"] as DataSet;

                int user_id = Convert.ToInt32(ds.Tables[0].Rows[0]["user_id"].ToString());

                //获取选择的出库清单
                List<dzs.Model.out_storageList> li = GetCboList(user_id, Convert.ToInt32(this.ddl_checkUser.SelectedValue));
                //将前边页已选择的出库清单加入
                if (Session["li_outList"] != null)
                {
                    List<dzs.Model.out_storageList> li_session = Session["li_outList"] as List<dzs.Model.out_storageList>;

                    foreach (dzs.Model.out_storageList o in li_session)
                    {
                        li.Add(o);
                    }

                    Session["li_outList"] = li;
                }
                else
                {
                    Session["li_outList"] = li;
                }

                BindGV2(li);
                BindGV();
            }

            //this.ddl_project.Enabled = true;
            this.txt_projectName.Enabled = true;
        }

        //出库申请单删除功能
        protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandArgument != null)
            {
                if (e.CommandName == "lbl_ol_del")
                {
                    List<dzs.Model.out_storageList> li = new List<Model.out_storageList>();
                    string mid = e.CommandArgument.ToString();

                    //从session中取出li
                    if (Session["li_outList"] != null)
                    {
                        List<dzs.Model.out_storageList> li_session = Session["li_outList"] as List<dzs.Model.out_storageList>;

                        foreach (dzs.Model.out_storageList o in li_session)
                        {
                            if (o.material_id != int.Parse(mid))
                            {
                                li.Add(o);
                            }
                        }

                        Session["li_outList"] = li;
                    }
                    BindGV2(li);
                }



            }
        }


        //导出复写
        public override void VerifyRenderingInServerForm(Control control)       //导出
        { }
        //导出excel
        protected void btn_out_Click(object sender, EventArgs e)
        {

            this.GridView2.Columns[0].Visible = false;

            if (this.GridView2.Rows.Count != 0)
            {
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "GB2312";
                Response.AppendHeader("Content-Disposition", "attachment;filename=cksqqd.xls");
                //Response.ContentEncoding = System.Text.Encoding.UTF7;
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                Response.ContentType = "application/ms-excel";
                System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
                Response.Output.Write("<H4 align='center'>出库申请清单</H4>");
                this.GridView2.RenderControl(oHtmlTextWriter);
                Response.Output.Write(oStringWriter.ToString());
                Response.Flush();
                Response.End();

            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('数据为空，无法导出表格')</script>");

            }

        }
        
	}
}